<template>
  <a-drawer :title="editTitle" width="90%" :visible="visible" @close="() => {
    this.visible = false
    this.data2 = [];
    this.allData = [];
  }
    " :body-style="{ paddingBottom: '200px' }">
    <a-form-model class="components-input-demo-size" ref="ruleForm" :model="entity" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="开票日期:" prop="CreateTime">
            <a-input v-model="entity.CreateTime" autocomplete="off" :disabled="true" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="发票代码" prop="DicKey">
            <a-input :disabled="details" v-model='entity.Invoicecode' autocomplete="off" placeholder="购买方" />
            <!-- <a-input :disabled="details" v-model="entity.DicKey" autocomplete="off" placeholder="购买方" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="发票号码" prop="zhanghu">
            <a-input :disabled="details" v-model="entity.Invoicenumber" autocomplete="off" placeholder="税号" />
            <!-- <a-input :disabled="details" v-model="entity.zhanghu" autocomplete="off" placeholder="税号" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="客户名称:" prop="cusname">
            <a-input v-model="this.cusname" autocomplete="off" :disabled="true" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="购买方" prop="DicKey">
            <a-input :disabled="details" v-model="entity.DicKey" autocomplete="off" placeholder="购买方" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="税号" prop="zhanghu">
            <a-input :disabled="details" v-model="entity.zhanghu" autocomplete="off" placeholder="税号" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="开户行及账号:" prop="kaihu">
            <a-input :disabled="details" v-model="entity.kaihu" autocomplete="off" placeholder="开户行" />
          </a-form-model-item>
        </a-col>

        <a-col :span="8">
          <a-form-model-item label="地址、电话" prop="phone">
            <a-input :disabled="details" v-model="entity.phone" autocomplete="off" placeholder="电话" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="说明:" prop="Remarks">
            <a-input :disabled="details" v-model="entity.Remarks" autocomplete="off" placeholder="说明" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <div style="padding-bottom: 5%;">
        <a-table ref="table" :scroll="{ x: 800 }" :columns="columns" :dataSource="data2" style="min-height: 20px;"
          :pagination="false" :rowKey="row => row.detailcode" :expandedRowRender="expandedRowRenderSon" :loading="loading"
          :bordered="true" :row-selection="details ? null : rowSelection" size="small">
          <span slot="OldOutboundOrder" slot-scope="text, record">
            <span v-if="text">{{ text }}</span>
            <span v-else><a-tag color="blue">待替换</a-tag></span>
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <!-- <a v-if="record.tihuanstate == '已替换'" @click="handleNewOdd(record)">新单</a> -->
              <!-- <a-divider v-if="record.tihuanstate == '已替换'" type="vertical" /> -->
              <!-- <a v-if="record.tihuanstate == '已替换'" @click="handleOldOdd(record)">原单</a> -->
              <a v-if="record.tihuanstate == '未替换'" @click="handleReplace(record)">替换</a>
              <a-switch v-else checked-children="新单明细" un-checked-children="原单明细" default-checked
                @change="changeEdit($event, record)" />
              <!-- <a v-if="record.State == 1 && record.edit" @click="handleSave(record)">保存</a>
              <a-divider v-if="record.State == 1 && record.edit" type="vertical" />
              <a v-if="record.State == 1 && record.edit" @click="handleCancel(record)">取消</a> -->
            </template>
          </span>
        </a-table>
      </div>
      <p></p>
      <a-row style="position: fixed; bottom: 5%;z-index: 999; width: 88%; background-color: #fff;">
        <!-- <p style="text-align: right;margin-right: 20px;">价税合计<span></span> {{ Amount | NumberFormats }}</p> -->
        <a-col :span="8">
          <a-form-model-item label="收票人:" prop="shoupiaoren">
            <a-select :disabled="details" v-model="entity.shoupiaoren">
              <a-select-option v-for="item in options" :key="item.value" :title="item.label">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="手机号:" prop="Phone">
            <a-input :disabled="details" v-model="entity.Phone" autocomplete="off" placeholder="收票人手机号" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="收票地址:" prop="shoupiaodizhi">
            <a-textarea :disabled="details" v-model="entity.shoupiaodizhi" autocomplete="off" placeholder="收票地址" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="备注" prop="beizhu">
            <a-textarea :disabled="details" v-model="entity.beizhu" autocomplete="off" placeholder="备注" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- </a-row>
          <a-row> -->

    </a-form-model>
    <div :style="{
      position: 'absolute',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '10px 16px',
      background: '#fff',
      textAlign: 'right',
      zIndex: 999999,
    }">
      <a-button type="primary" @click="close">取消</a-button>

    </div>
    <a-drawer :title="titles" width="80%" placement="right" :visible="visiblee" @close="closeReplace" :body-style="{ paddingBottom: '80px' }">
      <div style="margin-bottom: 10px;" class="table-page-search-wrapper">
        <h2>客户:{{ this.cusname }}</h2>
        <a-input style="width: 200px;margin-right: 8px;" v-model="OutboundOrder" placeholder="出库单号"
          @keydown.enter="getReplaceData" />
        <a-button type="primary" @click="() => {
          this.pagination.current = 1
          this.getReplaceData()
        }">查询</a-button>
      </div>
      <a-table ref="table" :scroll="{ x: 600 }" :columns="columnss" :rowKey="(row) => row.OutboundOrder"
        :dataSource="data" :pagination="paginationReplace" :expandedRowRender="expandedRowRender" :loading="loading1"
        @change="handleTableChangeReplace" :rowSelection="rowSelection1" :bordered="true" size="small">
      </a-table>
      <div :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }">
        <a-button type="primary" :style="{ marginRight: '8px' }" @click="() => {
          this.visiblee = false

        }">取消</a-button>
        <a-button type="primary" @click="handleOk">下一步</a-button>
      </div>
    </a-drawer>
    <a-drawer title="新出库单明细" width="80%" :visible="modalVisible" @close="() => {
      this.modalVisible = false
    }">
      <a-table ref="table" :scroll="{ y: tableHeight, x: 1350 }" :columns="columns2" :dataSource="changeData"
        :pagination="false" :rowKey="row => row.detailcode" :loading="loading" :bordered="true"
        :row-selection="details ? null : rowSelection" size="small">

        <template slot="TM_Name" slot-scope="text, record">
          <CompanySelect style="width: 100%;" v-model="record.TM_Name" :UnitGroupId="record.ventorycode"
            @select="project($event, record)"></CompanySelect>
        </template>
        <template slot="Price" slot-scope="text, record">
          <a-input style="width:100%" v-model="record.Price" @change="(e) => handlePriceChange(e, record)"></a-input>
        </template>
        <template slot="numskk" slot-scope="text, record, index">
          <a-input-number style="width:100%" v-model="record.numskk"
            @change="(e) => handleValChange(e, record, index)"></a-input-number>
        </template>
        <template slot="markup" slot-scope="text, record">
          <template>
            <a-input-number style="width:80%" v-model="record.markup"
              @change="(e) => handleValChange(e, record, index, true)"></a-input-number><span>%</span>
          </template>
        </template>
      </a-table>
      <div :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }">
        <a-button type="primary" :style="{ marginRight: '8px' }" @click="() => {
          this.modalVisible = false
        }">取消</a-button>
        <a-button type="primary" @click="handleSave">保存</a-button>
      </div>
    </a-drawer>
  </a-drawer>
</template>

<script>
import CompanySelect from '@/components/PB/CompanySelect'

const columns = [
  { title: '出库单号', dataIndex: 'OutboundOrder',width:'200px' },
  { title: '原出库单号', dataIndex: 'OldOutboundOrder',width:'180px', scopedSlots: { customRender: 'OldOutboundOrder' }},
  { title: '开票数量', dataIndex: 'InvoicingQuantity', align: 'right', scopedSlots: { customRender: 'numskk' }, width: '200px' },
  { title: '开票金额', dataIndex: 'InvoicingAmount',scopedSlots: { customRender: 'InvoicingAmount' },align: 'right',  width: '200px',},
  { title: '税额', dataIndex: 'TaxAmount', align: 'right', width: '200px' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '100px',align:'center' },
].filter(v => !v.hidden); // 增加filter过滤
const columnss = [
  { title: '出库单号', dataIndex: 'OutboundOrder'},
  { title: '单据日期', dataIndex: 'TIME'},
  { title: '摘要', dataIndex: 'Memo'},
].filter(v => !v.hidden); // 增加filter过滤
const columns2 = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px',
  },
{ title: '出库单号', dataIndex: 'code', width: '30%' ,hidden: true, },
{ title: '货物编码', dataIndex: 'ventorycode', width: '100px' },
{ title: '货物名称', dataIndex: 'ventoryname', width: '100px' },
{ title: '规格型号', dataIndex: 'specification', width: '100px' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px' },
  { title: '出库数量', dataIndex : 'quantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', width: '100px', align: 'right' ,hidden:true},
  { title: '已开数量', dataIndex: 'Openedquantity', width: '100px', align: 'right' },
  { title: '开票使用名称', dataIndex: 'TM_Name', width: '150px', scopedSlots: { customRender: 'TM_Name' } },
  { title: '基本售价', dataIndex: 'origTaxSalePrice', width: '100px', align: 'right' },
  { title: '加成率%', dataIndex: 'markup', width: '150px', align: 'right', scopedSlots: { customRender: 'markup' } },
  { title: '开票价格', dataIndex: 'Price', width: '200px', align: 'right', scopedSlots: { customRender: 'Price' } },
  { title: '数量', dataIndex: 'numskk', width: '100px', align: 'right', scopedSlots: { customRender: 'numskk' } },
  { title: '金额', dataIndex: 'kmoneys', width: '200px', align: 'right' },
  { title: '税率', dataIndex: 'TaxRate', width: '100px', align: 'right' },
  { title: '税额', dataIndex: 'TaxPrice', width: '200px', align: 'right' },
].filter(v => !v.hidden); // 增加filter过滤
const columnsSon = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width:'70px',fixed:'left'
  },
  { title: '货物编码', dataIndex: 'InventoryCode'},
  { title: '货物名称', dataIndex: 'InvoicingName' },
  { title: '货物规格', dataIndex: 'Inventoryspec' },
  { title: '单位', dataIndex: 'Inventoryunit',width:'100px' },
  { title: '基本售价', dataIndex: 'InventoryPrice', align: 'right' },
  { title: '加成率', dataIndex: 'Markup', align: 'right', scopedSlots: { customRender: 'Markup' } },
  { title: '开票价格', dataIndex: 'InvoicingPrice', align: 'right', scopedSlots: { customRender: 'Markup' } },
  { title: '数量', dataIndex: 'InvoicingQuantity',width:'100px', align: 'right'},
  {
    title: '含税金额', dataIndex: 'PriceAmount', align: 'right'
  },
].filter(v => !v.hidden); 
const columnsReplace = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width:'70px',fixed:'left'
  },
   { title: '出库单号', dataIndex: 'code', width: '150px', hidden: true, },

{ title: '货物编码', dataIndex: 'ventorycode' },
  { title: '货物名称', dataIndex: 'ventoryname' },
  { title: '货物规格', dataIndex: 'specification' },
  { title: '单位', dataIndex: 'compositionQuantity' },
  { title: '批次', dataIndex: 'batch' },
  { title: '出库数量', dataIndex: 'quantity', align: 'right' },
  { title: '已开数量', dataIndex: 'Openedquantity', align: 'right' },
  { title: '未开数量', dataIndex: 'Unopenedquantity', align: 'right' },
  { title: '价格', dataIndex: 'origTaxSalePrice', align: 'right' },
  { title: '含税金额', dataIndex: 'origTaxSaleAmount', align: 'right',hidden:true}
].filter(v => !v.hidden); 
export default {
  components: {
    CompanySelect
  },
  props: {
    parentObj: Object
  },
  data() {
    return {
      data: [],
      selectedRowKeys: [],
      columns,
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      paginationReplace: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'ID', order: 'desc' },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      columnss,
      visible: false,
      details: true,
      visiblee: false,
      loading: false,
      data2: [],
      entity: {},
      rules: {},
      data: [],
      Amount: 0,
      CusId: '',
      title: '',
      modalVisible:false,
      cusname: '',
      loading1: false,
      id: '',
      newId: '',
      filters: null,
      changeData:[],
      itemId: '',
      oldData:[],
      columns2,
      columnsReplace,
      columnsSon,
      dataSon:{},
      OutboundOrder:'',
      loadingSon:false,
      titles:'',
      editTitle:'',
      replaceId:'',
      newOddNumber:'',
    }
  },
  computed: {
    rowSelection1() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        type:'radio'
      }
    },
  },
  methods: {
    close() {
      this.visible = false
      this.entity = {}
    },
    init() {
      this.visible = true
    },
    openForm(id, title) {
      this.init()
      if (id) {
        this.loading = true
        this.id = id;
        this.getDataList();
      }
    },
    closeReplace(){
      this.OutboundOrder = '';
      this.visiblee = false;
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    handleTableChangeReplace(pagination, filters, sorter) {
      this.paginationReplace = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getReplaceData()
    },
    getDataList() {
      this.data2 = [];
      this.loading = true;
      this.$http.post('/InvoiceManagement/v_abnormalinvoice/GetTheData',{id:this.id}).then(resJson => {
        let data = resJson.Data;
        
        this.cusname = data.CusName
        this.editTitle  = '申请单号:'+data.Code
        this.entity.DicKey = data.TicketbuyerName
        this.entity.zhanghu = data.TaxRegcode//税号
        this.entity.kaihu = data.Accbank//开户行
        this.entity.phone = data.CusAddress
        this.entity.Remarks = data.Memo
        this.entity.shoupiaoren = data.PayeeUserName
        this.entity.Phone = data.PayeeUserPhone
        this.entity.shoupiaodizhi = data.PayeeUserAddres
        this.entity.beizhu = data.Remark
        this.entity.CreateTime = data.CreateTime.slice(0,10)
        this.entity.Invoicecode = data.Invoicecode
        this.entity.Invoicenumber = data.Invoicenumber
        this.Amount = data.Amountincludingtax
        this.CusId = data.CusId;
        this.CusCode = data.CusCode;
        this.$http.post('/InvoiceManagement/v_abnormaloutbound/GetDataList',{
          "PageIndex": 1,
          "PageRows": 10000,
          "SortField": "Id",
          "SortType": "desc",
          "Search": {
            "ParentId": this.id
          }
        }).then(res=>{
          this.loading = false
          this.data2 = res.Data;
          this.data2.forEach(item=>{
            item.edit = true;
            item.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount)
            item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
          })
        }).catch(err=>{
          this.$message.error(err)
        })
        // data.Details.forEach(item => {
        //   let obj = {};
        //   obj.code = item.OutboundOrder;
        //   obj.detailcode = item.OutboundOrderDetails;
        //   obj.id = item.InventoryId;
        //   obj.ventoryname = item.InventoryName;
        //   obj.origTaxSalePrice = this.$options.filters.NumberFormats(item.InventoryPrice);
        //   obj.compositionQuantity = item.Inventoryunit;
        //   obj.specification = item.Inventoryspec;
        //   obj.numskk = item.InvoicingQuantity;
        //   obj.Price = item.InvoicingPrice;
        //   obj.kmoneys = this.$options.filters.NumberFormats(item.InvoicingAmount);
        //   obj.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount);
        //   obj.ventorycode = item.InventoryCode;
        //   obj.TM_Name = item.InvoicingName;
        //   obj.TaxRate = item.TaxRate + '%';
        //   obj.TaxPrice = this.$options.filters.NumberFormats(item.TaxAmount);
        //   obj.markup = item.Markup;
        //   obj.OutboundOrder = item.OutboundOrder;
        //   obj.OldOutboundOrder = item.OldOutboundOrder;
        //   obj.State = item.State;
        //   obj.Id = item.Id;
        //   obj.OldId = item.Id;
        //   obj.ParentId = item.ParentId;
        //   this.data2.push(obj);
        //   this.oldData.push(JSON.parse(JSON.stringify(obj)));
        // })
      }).catch(err => {
        this.$message.error(err)
      })
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    //保存
    handleSave(record) {
      console.log(this.changeData)
       let flag = false;
      let flag1 = false;
      let flag2 = false;
      let arr =[];
      this.changeData.forEach(item=>{
        let reg = /^\d+(\.\d{0,8})?$/;
     
      if ((item.quantity - item.Openedquantity) < item.numskk) {
        flag = true;
      }
      if (!item.numskk || !item.TM_Name || !item.Price) {
        flag1 = true;
      }
      if (!reg.test(item.Price)) {
        flag2 = true
      }
      
        let obj = {};
       obj.OutboundOrder= item.code;//选择的新出库单号
      obj.OutboundOrderDetails= item.detailcode;//选择的新出库单明细Id
      obj.InvoicingQuantity= item.numskk;//开票数量
      obj.InvoicingPrice=item.Price;//开票单价
      obj.InvoicingAmount= item.kmoneys;//开票总额
      obj.TaxAmount=item.TaxPrice;//税额
      obj.InventoryId=item.idinventory;//货物id
      obj.InventoryName=item.ventoryname;//货物名称
      obj.InventoryCode= item.ventorycode;//货物编码
      obj.Inventoryunit=item.compositionQuantity;//货物单位
      obj.Inventoryspec=item.specification;//货物规格
      obj.InventoryPrice= item.origTaxSalePrice;//基本售价
      obj.InvoicingName= item.TM_Name;//开票名称
      obj.InvoicingCode= item.Taxproductcode; //选择开票编码
      obj.Invoicingunit= item.TM_Unit;//选择开票单位
      obj.Invoicingspec= item.TM_Specs;//选择开票规格
      obj.InvoicingId= item.TaxproductId; //选择开票id
      obj.OldOutboundOrder=this.oldOddNumber; //原始出库单号
      obj.Markup= item.markup;// 加成率
      arr.push(obj);
      })
      if (flag1) {
        this.$message.warning('信息请填写完毕')
        return;
      }
      if (flag2) {
        this.$message.warning('请输入正确的价格，最多八位小数')
        return;
      }
      if (flag) {
        this.$message.warning('数量不能大于出库-已开')
        return;
      }
     let boby =  {
    "Id": this.id,
    "OldOutboundOrder": this.oldOddNumber, //旧出库单号
    "NewOutboundOrder": this.newOddNumber ,// 新出库单号
    "details": arr
      }
      this.$http.post('/InvoiceManagement/Inv_Invoicing/ReplaceInvoicing',boby).then(res=>{
        if(res.Success){
           this.$message.success('保存成功!')
          this.getDataList();
          this.modalVisible =false;
        }
       

      }).catch(err=>{
        this.$message.error(err)
      })
    },
    //替换里的深层
    expandedRowRender(record){
            //获取第一层数据
            if(this.dataSon[record.Id]){
                return (
                    <a-table
                        columns={this.columnsReplace}
                        data-source={this.dataSon[record.Id]}
                        pagination={false}
                        scroll={{ x: 800 }}
                        loading={this.loadingSon}
                        v-on:change={()=>{console.log(123)}}
                    ></a-table>
                );
            }
            this.loadingSon = true;
            this.$http.post('/InvoiceManagement/ST_RDRecord_b/GetRDRecordList', {
                PageIndex: 1,
                PageRows: 10000,
                SortField: 'Code',
                SortType: 'desc',
                Search: {
                    "OutboundOrders": [record.OutboundOrder]
                }
            }).then(res=>{
                this.loadingSon = false;
                this.dataSon[record.Id] = res.Data
                this.dataSon[record.Id].forEach(item=>{
                  item.origTaxSalePrice = this.$options.filters.NumberFormats(item.origTaxSalePrice)
                })
                this.$forceUpdate();
            }).catch(err=>{
                this.$message.error(err)
            })
            return (
                    <a-table
                        columns={this.columnsReplace}
                        scroll={{ x: 800 }}
                        data-source={this.dataSon[record.Id]}
                        pagination={false}
                        v-on:change={()=>{console.log(123)}}
                    ></a-table>
                );
        },
    expandedRowRenderSon(record){
            //获取第一层数据
            if(this.dataSon[record.Id]){
                return (
                    <a-table
                        columns={this.columnsSon}
                        scroll={{ x: 800 }}
                        data-source={this.dataSon[record.Id]}
                        pagination={false}
                    >
                    </a-table>
                );
            }
            this.loadingSon = true;
            this.$http.post('/InvoiceManagement/v_abnormaloutbound/GetInvoicingDetails', {
                PageIndex: 1,
                PageRows: 10000,
                SortField: 'id',
                SortType: 'desc',
                Search: {
                    "ParentId": record.ParentId,
                    "OutboundOrder": record.OutboundOrder
                }
            }).then(res=>{
                this.loadingSon = false;
                this.dataSon[record.Id] = res.Data
                this.dataSon[record.Id].forEach(item=>{
                    item.InventoryPrice = this.$options.filters.NumberFormatss(item.InventoryPrice)
                    item.InvoicingPrice = this.$options.filters.NumberFormatss(item.InvoicingPrice)
                    item.PriceAmount = this.$options.filters.NumberFormats(item.TaxAmount+Number(item.InvoicingPrice))
                    item.Markup = item.Markup+'%'
                })
                this.$forceUpdate();
            }).catch(err=>{
                this.$message.error(err)
            })
            return (
                    <a-table
                        columns={this.columnsSon}
                        scroll={{ x: 800 }}
                        data-source={this.dataSon[record.Id]}
                        pagination={false}
                    >
                    
                    </a-table>
                );
        },
    project(select, record) {
      console.log(select)
      if (select.Taxproductname) {
        record.TM_Name = select.Taxproductname;
        record.TaxproductId = select.TaxproductId;
        record.Taxproductcode = select.Taxproductcode;
        record.TM_Unit = select.TM_Unit;
        record.TM_Specs = select.TM_Specs;
        record.TM_UnitPrice = select.TM_UnitPrice;
      }
      record.origTaxSalePrice = select.TM_UnitPrice;
      this.handleValChange(null, record, null, true);
      this.$forceUpdate();
    },
    //取消
    handleCancel(record){
      console.log(record,this.oldData,record.Id)
      let old =  JSON.parse(JSON.stringify(this.oldData.filter(item => item.Id == record.Id)[0]));
      
      this.data2.forEach((item,index)=>{
        if(item.Id== old.Id){
          this.data2.splice(index,1,old);
        }
      })
    //  this.getDataList();
    },
    getReplaceData(){
      this.data = [];
      this.loading1 = true;
      this.$http.post('/InvoiceManagement/v_outdata/GetDataList', {
        PageIndex: this.paginationReplace.current,
        PageRows: this.paginationReplace.pageSize,
        SortField: 'Time',
        SortType: 'desc',
        Search: {
           Code:this.CusCode, 
            OutboundOrder:this.OutboundOrder,
            // OutboundOrder:,
          },
        ...this.filters,
      }).then(res => {
        this.loading1 = false;
        this.data = res.Data
        this.data.forEach(item=>{
          item.TIME = item.TIME.slice(0,10)
        })
        if (this.data) {
          const pagination = { ...this.pagination }
          pagination.total = res.Total
          this.pagination = pagination
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    handleReplace(record) {
      this.visiblee = true;
      this.replaceId = record.Id
      this.itemId = record.id;
      this.selectedRowKeys = [];
      this.titles = '原出库单号:'+record.OutboundOrder
      this.oldOddNumber = record.OutboundOrder;
      this.getReplaceData();
    },
    timeFormat (val) { // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },
    //下一步
    handleOk() {
      if(this.selectedRowKeys.length<1){
        this.$message.error('请选择一个出库单号')
        return;
      }
      console.log(this.selectedRowKeys)
      this.newOddNumber = this.selectedRowKeys[0];
      this.$http.post('/InvoiceManagement/ST_RDRecord_b/GetRDRecordList', {
                PageIndex: 1,
                PageRows: 10000,
                SortField: 'Code',
                SortType: 'desc',
                Search: {
                    "OutboundOrders": [this.selectedRowKeys[0]]
                }
            }).then(res=>{
                this.changeData = res.Data;
                this.changeData.forEach(item=>{
                 
              this.$http
                .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRDRecordList', {
                  "PageIndex": 1,
                  "PageRows": 20,
                  "SortField": "TaxproductId",
                  "SortType": "desc",
                  "Search": {
                    "Keyword": item.ventorycode
                  }
                })
                .then((resJson) => {
                  console.log(resJson,item)
                   item.TaxRate = 3 + "%";
                  item.TaxPrice = Number(0).toFixed(8);
                  item.kmoneys = Number(0).toFixed(8)
                  item.TM_Name = resJson.Data[0].Taxproductname;
                  item.TaxproductId = resJson.Data[0].TaxproductId;
                  item.Taxproductcode = resJson.Data[0].Taxproductcode;
                  item.TM_Unit = resJson.Data[0].TM_Unit;
                  item.TM_Specs = resJson.Data[0].TM_Specs; 
                  item.origTaxSalePrice = resJson.Data[0].TM_UnitPrice;
                  item.TM_UnitPrice = resJson.Data[0].TM_UnitPrice;
                   item.markup = 100;
                  item.numskk = item.Unopenedquantity;
                  this.handleValChange(null,item,null,true)
                  this.$forceUpdate();
                })
            })
            }).catch(err=>{
                this.$message.error(err)
            })
      this.visiblee = false;
      this.modalVisible = true;
    },
    async changeEdit(e,record){
      let arr = [];
      if(e){
         
      let res =  await this.$http.post('/InvoiceManagement/v_invoicesdetail/GetVoidInvoicingList',{
            "PageIndex": 1,
            "PageRows": 10000,
            "SortField": "CreateTime",
            "SortType": "desc",
            "Search": {
            "ParentId":record.ParentId,
            "NewOutboundOrder": record.OutboundOrder,
            "Type": 1
          }
        })
       arr = res.Data
       arr.forEach(item=>{
        item.InventoryPrice = this.$options.filters.NumberFormats(item.InventoryPrice)
        item.InvoicingPrice = this.$options.filters.NumberFormats(item.InvoicingPrice)
        item.PriceAmount = this.$options.filters.NumberFormats(item.TaxAmount+Number(item.InvoicingPrice))
        item.Markup = item.Markup+'%'
       })
      }else{
         
      let  res =  await this.$http.post('/InvoiceManagement/v_invoicesdetail/GetVoidInvoicingList',{
          "PageIndex": 1,
          "PageRows": 10000,
          "SortField": "CreateTime",
          "SortType": "desc",
          "Search": {
          "ParentId": record.ParentId,
          "OldOutboundOrder": record.OldOutboundOrder,
          "Type": 0
        }
      })
       arr = res.Data
        arr.forEach(item=>{
          item.InventoryPrice = this.$options.filters.NumberFormats(item.InventoryPrice)
          item.InvoicingPrice = this.$options.filters.NumberFormats(item.InvoicingPrice)
          item.PriceAmount = this.$options.filters.NumberFormats(item.TaxAmount+Number(item.InvoicingPrice))
          item.Markup = item.Markup+'%'
       })
      }
       this.dataSon[record.Id] = arr;
        console.log(this.dataSon[record.Id])
        this.$forceUpdate();
    },
    //价格框输入
    handlePriceChange(val, item) {
      let reg = /^\d+(\.\d{0,8})?$/;
      console.log(reg.test(val), val.target.value)
      if (reg.test(val.target.value)) {
        // item.Price = Number(val.target.value)
      } else {
        this.$message.warning('请输入正确的价格，最多八位小数')
        return;
      }
      item.markup = (Number(val.target.value) / item.TM_UnitPrice * 100) ? (Number(val.target.value) / item.TM_UnitPrice * 100).toFixed(4) : 0
      this.handleValChange(null, item);
    },
    //精度丢失计算
    actionOperationResult(val1, val2, val3) {
      console.log(val1, val2)
      const p = this.actionOperation(val1, val2, val3);
      return ((val1 * p) * (val2 * p)) * ((val3 * p) || 1) / (p * p * (val3 ? p : 1));
    },
    actionOperation(val1, val2, val3) {
      const len1 = val1.toString().length - val1.toString().indexOf(".") - 1;
      const len2 = val2.toString().length - val2.toString().indexOf(".") - 1;
      let p = 0;
      if (val3) {
        const len3 = val3.toString().length - val3.toString().indexOf(".") - 1;
        p = Math.max(len1, len2, len3);
      } else {
        p = Math.max(len1, len2);
      }

      // 避免最终求出结果的长度大于最大长度的时候导致精度丢失 开启下面
      // p += p - Math.min(len1, len2); 
      return Math.pow(10, p);
    },
    handleValChange(val, item, index, f) {
      if (item.markup < 0) {
        item.markup = 0;
      }
      if (item.numskk < 0) {
        item.numskk = 0;
      }
      if (f) {
        item.Price = (item.markup * item.TM_UnitPrice / 100) ? (item.markup * item.TM_UnitPrice / 100).toFixed(8) : 0
      }
      let kmoneys = 0
      //计算金额
      if (item.Price && Number(item.numskk)) {
        console.log(this.actionOperationResult(item.Price, Number(item.numskk)))
        kmoneys = (this.actionOperationResult(item.Price, Number(item.numskk))).toFixed(8)
      }
      //计算税额
      if (kmoneys) {
        console.log(this.$options.filters.NumberFormats(kmoneys))
        item.kmoneys = this.$options.filters.NumberFormats(kmoneys);
        item.TaxPrice = this.$options.filters.NumberFormats(this.actionOperationResult(Number(kmoneys), (item.TaxRate.replace("%", "") / 100)));
        //清空合计
        this.Amount = 0;
        //计算合计
        this.data2.forEach(ite => {
          if (ite.Price && ite.TaxPrice) {
            //精度
            // console.log(this.Amount, Number(ite.kmoneys.replace(/,/g, '')), Number(ite.TaxPrice.replace(/,/g, '')))
            this.Amount = (((this.Amount * this.precision + Number(ite.kmoneys.replace(/,/g, '')) * this.precision + Number(ite.TaxPrice.replace(/,/g, '')) * this.precision) / this.precision)).toFixed(8);
            // this.Amount = this.Amount  + Number(ite.kmoneys.replace(',', '')) + Number(ite.TaxPrice.replace(',', '')) ;
          }
          console.log(this.Amount)
        })
      }
      this.$emit('input', [...this.data2])
      this.$forceUpdate();
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .heji {
  position: sticky;
  bottom: 0;
  background: #fff;
  font-size: 19px;
  font-weight: bold;
}

.components-input-demo-size .ant-input {
  margin: 0;
}

::v-deep .ant-btn .ant-btn-primary {
  z-index: 99999;
}

/deep/ td {
  background: #fff;
}
</style>
